import { BadRequestException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { hash, verify } from 'argon2';
import { PrismaService } from 'src/prisma/prisma.service';
import loginDto from './dto/login.dto';
import RegisterDto from './dto/register.dto';

@Injectable()
export class AuthService {
  constructor(private prisma: PrismaService, private jwt: JwtService) {}

  async register(dto: RegisterDto) {
    const user = await this.prisma.user.create({
      data: {
        name: dto.name,
        password: await hash(dto.password),
      },
    });

    return this.token(user);
    // return {
    //   code: 201,
    //   message: '注册成功',
    // };
  }

  async login(dto: loginDto) {
    // findUnique是按唯一值来查找
    const user = await this.prisma.user.findUnique({
      where: {
        name: dto.name,
      },
    });
    if (!user) throw new BadRequestException('用户不存在');

    // 比对密码 user.password数据库存储的加密密码, dto.password表单提供的密码
    if (!(await verify(user.password, dto.password)))
      throw new BadRequestException('输入密码有误');
    return this.token(user);
  }

  private async token({ name, id }) {
    return {
      token: await this.jwt.signAsync({
        name,
        sub: id,
      }),
    };
  }
}
